package com.gy.ai.agent.client;

import com.alibaba.fastjson2.JSON;
import com.gy.ai.agent.listener.ReqClientListener;
import com.gy.ai.agent.util.SysOkHttpClientUtil;
import com.gy.ai.agent.util.SysUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

/**
 * @author LGY
 * Create by 2025/6/16 15:09
 */
@Slf4j
public class SseClient extends EventSourceListener implements BaseReqClient {

    private OkHttpClient okHttpClient;
    private EventSource eventSource;
    private ReqClientListener listener;
    private boolean isStop = false;

    @Override
    public void start(String url, Map<String, String> headers, String payload, ReqClientListener listener) {
        this.listener = listener;
        this.isStop = false;
        Request.Builder builder = new Request.Builder()
                .url(url);
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(builder::addHeader);
        }
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(payload, mediaType);
        Request request = builder.post(body).build();
        this.okHttpClient = SysOkHttpClientUtil.buildDefaultClient();
        EventSource.Factory factory = EventSources.createFactory(this.okHttpClient);
        this.eventSource = factory.newEventSource(request, this);
        log.info("消息发送载体: {}", payload);
        this.listener.onStart(this);
    }

    @Override
    public void stop() {
        tryToStop();
    }

    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        tryToStop();
    }

    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        log.info("消息接收载体:{}",  JSON.toJSONString(data));
        this.listener.onMessage(this, data);
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        try {
            this.listener.onFailure(this, SysUtil.getFailureThrowable(t, response));
        } finally {
            tryToStop();
        }
    }

    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        //super.onOpen(eventSource, response);
    }


    private boolean tryToStop() {
        if (!this.isStop) {
            try {
                this.isStop = true;
                this.listener.onStop(this);
            } finally {
                if (eventSource != null) {
                    eventSource.cancel();
                }
                if (okHttpClient != null) {
                    okHttpClient.dispatcher().executorService().shutdown();
                }
            }
            return true;
        }
        return false;
    }
}
